package com.zpark.cloud.alibaba.service.impl;

import com.zpark.cloud.alibaba.entity.Account;
import com.zpark.cloud.alibaba.mapper.IAccountMapper;
import com.zpark.cloud.alibaba.service.IAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 账户业务层接口实现类
 */
@Service
@Slf4j
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountMapper accountMapper;


    /**
     * 减少账户余额（修改账户余额信息）
     * @param uid 用户id
     * @param money 后买商品的价格
     * @return
     */
    @Override
    public Integer decreaseResidue(Long uid, BigDecimal money) {
        log.info("------->account-service 开始查询账户余额");
        // 根据用户id查询账户数据
        Account account = accountMapper.selectByUserId(uid);
        log.info("------->account-service 账户余额查询完成，" + account);

        // 判断账户余额是否充足，如果余额不足，则提示
        if (account == null || account.getResidue().intValue() < money.intValue()) {
            log.info("------->account-service  账户余额不足，开始回滚！");
            throw new RuntimeException("账户余额不足");
        }

        // 余额充足，修改账户
        log.info("------->account-service 开始从账户余额中扣钱！");

        // 创建修改账户对象
        Account changeAccount = new Account();
        // 为属性赋值
        changeAccount.setId(account.getId());
        changeAccount.setUserId(uid);
        changeAccount.setTotal(account.getTotal());
        changeAccount.setUsed(account.getUsed().add(money));
        changeAccount.setResidue(account.getResidue().subtract(money));

        // 调用持久层接口实现功能
        int row = accountMapper.updateByPrimaryKey(changeAccount);
        if (row <= 0) {
            log.info("------->account-service  修改账户失败，开始回滚！");
            throw new RuntimeException("修改账户失败，原因未知");
        }

        log.info("------->account-service 从账户余额中扣钱完成");

        return row;
    }
}
